package com.xyz.code.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MyFileUtil {
	// 模板文件读取
	public static String getTemplate(String template) throws IOException {
		StringBuffer context = new StringBuffer();
		File tmpFile = new File(template);
		String tmp = null;
		BufferedReader breader = null;
		try {
			breader = new BufferedReader(new InputStreamReader(
					ClassLoader.getSystemResourceAsStream(template)));
			// breader = new BufferedReader(new InputStreamReader(new
			// FileInputStream(tmpFile)));
			while ((tmp = breader.readLine()) != null) {
				context.append(tmp + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			breader.close();
		}
		return context.toString();
	}

	// 模板内容替换
	public static String getContextByTemplate(Object obj, String template)
			throws IOException, SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		Class<?> clazz = obj.getClass();
		String context = MyFileUtil.getTemplate(template); // 得到模板内容
		Set<String> set = new HashSet<String>();

		int i = 0;
		while (i < context.length()) {
			int index = context.indexOf("${", i);
			int end = context.indexOf("}", index);
			if (index == -1)
				break; // 找不到以${开头 中止循环
			set.add(context.substring(index + 2, end).trim()); // 取得${mobile} 的
																// 'mobile' 字符串
			i = end;
		}

		Map<String, String> mapTemp = new HashMap<String, String>();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			String tmp = iterator.next();
			String value = BeanUtils.getProperty(obj, tmp);
			mapTemp.put(tmp, value); // 如map.put("mobile","13560023645");
		}

		for (Map.Entry<String, String> entry : mapTemp.entrySet()) {
			// 替换模板中的类似${mobile}的占位符 为真正的字符.。
			if (entry.getValue() != null)
				context = context.replaceAll("\\$\\{" + entry.getKey() + "\\}",
						entry.getValue());
		}
		return context;
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

}
